package com.sikaryofficial.auth.service;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson2.JSON;
import com.sikaryofficial.auth.config.HiSMKAuthConfig;
import com.sikaryofficial.auth.config.SourcePointsVO;
import com.sikaryofficial.auth.config.UserConfig;
import com.sikaryofficial.auth.constant.AuthConstants;
import com.sikaryofficial.auth.form.LoginChannelBody;
import com.sikaryofficial.auth.form.LoginH5Body;
import com.sikaryofficial.auth.form.RegisterChannelBody;
import com.sikaryofficial.auth.form.RegisterH5Body;
import com.sikaryofficial.auth.form.mapping.RegisterMapping;
import com.sikaryofficial.auth.mapper.ChannelUserMapping;
import com.sikaryofficial.auth.mapper.SysUserOauthMapping;
import com.sikaryofficial.common.core.constant.CacheConstants;
import com.sikaryofficial.common.core.constant.ChannelEnum;
import com.sikaryofficial.common.core.constant.Constants;
import com.sikaryofficial.common.core.constant.DeviceIdEnum;
import com.sikaryofficial.common.core.constant.HttpStatus;
import com.sikaryofficial.common.core.constant.SecurityConstants;
import com.sikaryofficial.common.core.constant.UserConstants;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.enums.UserStatus;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.text.Convert;
import com.sikaryofficial.common.core.utils.DateUtils;
import com.sikaryofficial.common.core.utils.ServletUtils;
import com.sikaryofficial.common.core.utils.StringUtils;
import com.sikaryofficial.common.core.utils.ip.IpUtils;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.common.security.service.TokenService;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.InnerNetSystemService;
import com.sikaryofficial.system.api.RemoteHiSMKDigDataService;
import com.sikaryofficial.system.api.RemotePointBalanceService;
import com.sikaryofficial.system.api.RemoteUserService;
import com.sikaryofficial.system.api.domain.SysUser;
import com.sikaryofficial.system.api.domain.UserReq;
import com.sikaryofficial.system.api.domain.customer.RegisterChannelBodyBO;
import com.sikaryofficial.system.api.model.LoginUser;
import com.sikaryofficial.system.api.model.ScanRegisterVO;
import com.sikaryofficial.system.api.model.channel.ChannelCompanyAddressReq;
import me.zhyd.oauth.model.AuthUser;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.sikaryofficial.common.core.constant.UserConstants.USERNAME_MAX_LENGTH;
import static com.sikaryofficial.common.core.utils.StringUtils.generateRandomString;

/**
 * 登录校验方法
 *
 * @author qinjinyuan
 */
@Component
public class SysLoginService {
    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);
    private static final Integer DEFAULT_AGE = 21;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private SysRecordLogService recordLogService;
    @Autowired
    private RedisService redisService;
    @Resource
    private UserConfig userConfig;
    @Autowired
    private TokenService tokenService;

    @Resource
    private HiSMKAuthConfig authConfig;

    @Autowired
    private RemotePointBalanceService remotePointBalanceService;
    @Resource
    private HiSMKAuthConfig sourcePointsConfig;

    @Autowired
    private InnerNetSystemService innerNetSystemService;

    @Autowired
    private RemoteHiSMKDigDataService hiSMKDigDataService;

    /**
     * 非密码登录
     */
    public LoginUser login(String username) {

        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username)) {
            // 用户/密码必须填写
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "User/password must be filled in");
            throw new ServiceException("User/password must be filled in");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            // 很遗憾，访问IP已被列入系统黑名单
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "Unfortunately, accessing IP has been blacklisted in the system");
            throw new ServiceException("Unfortunately, accessing IP has been blacklisted in the system");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            // 登录用户不存在
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "Login user does not exist");
            throw new ServiceException("Login user does not exist:" + username);
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        // 年龄缓存设置
        buildUserAge(user);
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            // 对不起，您的账号已被删除
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "Sorry, your account has been deleted");
            throw new ServiceException("Sorry, your account has been deleted: " + username);
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            // 对不起，您的账号已停用
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "Sorry, your account has been deactivated");
            throw new ServiceException("Sorry, your account has been deactivated:" + username);
        }
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "Login succeeded");
        return userInfo;
    }

    /**
     * 登录
     */
    public LoginUser login(String username, String password) {

        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            // 用户/密码必须填写
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "User/password must be filled in");
            throw new ServiceException("User/password must be filled in");
        }

        if (StringUtils.isAnyBlank(username, password)) {
            // 用户/密码必须填写
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "User/password must be filled in");
            throw new ServiceException("User/password must be filled in");
        }

        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            // 用户密码不在指定范围
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "The user password is not within the specified range");
            throw new ServiceException("The user password is not within the specified range");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            // 很遗憾，访问IP已被列入系统黑名单
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "Unfortunately, accessing IP has been blacklisted in the system");
            throw new ServiceException("Unfortunately, accessing IP has been blacklisted in the system");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            // 登录用户不存在
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "Login user does not exist");
            throw new ServiceException("Login user does not exist:" + username);
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        // 年龄缓存设置
        buildUserAge(user);
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            // 对不起，您的账号已被删除
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "Sorry, your account has been deleted");
            throw new ServiceException("Sorry, your account has been deleted: " + username);
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            // 对不起，您的账号已停用
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "Sorry, your account has been deactivated");
            throw new ServiceException("Sorry, your account has been deactivated:" + username);
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "Login succeeded");
        return userInfo;
    }

    private void buildUserAge(SysUser user) {
        // 缓存设置
        // 查看年龄是否满足限制
        String catchKey = MessageFormat.format(CacheConstants.USER_AGE_KEY, user.getUserId().toString());
        log.info("buildUserAge_catchKey: {}", catchKey);
        if (Objects.nonNull(user.getBirthDate())) {
            log.info("buildUserAge_buildUserAge: {}", user.getBirthDate());
            redisService.setCacheObject(catchKey, DateUtils.getAgeByBirthDate(user.getBirthDate()));
        }
    }

    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "Logout succeeded");
    }

    /**
     * 注册
     */
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        // 新增出生日期字段
        sysUser.setBirthDate(DateUtils.parseDate(userConfig.getDefaultBirthDate()));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    /**
     * H5 注册
     */
    public void registerForThird(RegisterH5Body registerBody, AuthUser authUser) {
        // 入参校验
        validParam(registerBody);
        // 设置默认source
        if (CharSequenceUtil.isBlank(registerBody.getSource())) {
            registerBody.setSource(authConfig.getDefaultSource());
        }
        String userName = buildUserName(registerBody, authUser.getUuid());
        // 注册用户信息
        SysUser sysUser = RegisterMapping.INSTANCE.coverToEntity(registerBody);
        sysUser.setPassword(SecurityUtils.encryptPassword(authConfig.getDefaultH5Pwd()));
        sysUser.setBirthDate(DateUtils.getBirthDateByAge(registerBody.getAge()));
        // h5注册 默认给她一个部门
        sysUser.setDeptId(authConfig.getDefaultDeptId());
        // 构建入参
        UserReq req = UserReq.builder()
                .sysUser(sysUser)
                .sysUserOauth(SysUserOauthMapping.INSTANCE.coverReqToEntity(authUser))
                .build();
        R<?> registerResult = remoteUserService.registerUserByH5(req, SecurityConstants.INNER);
        if (R.FAIL == registerResult.getCode()) {
            log.error("register fail：" + registerResult.getMsg());
            // 注册失败，记录错误信息
            recordLogService.recordLogininfor(userName, Constants.REGISTER, registerResult.getMsg());
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(userName, Constants.REGISTER, "注册成功");
    }

    /**
     * 构建用户名称和email地址
     *
     * @param registerBody
     * @return
     */
    private String buildUserName(RegisterH5Body registerBody, String uuid) {
        registerBody.setUsername(registerBody.getEmailAddress());
        String username = registerBody.getEmailAddress();
        if (CharSequenceUtil.isBlank(registerBody.getEmailAddress())) {
            // 注册使用 uuid作为用户名，确保唯一性
            registerBody.setUsername(uuid);
            username = registerBody.getUsername();
        }
        String shortUserName = username.indexOf("@") > 0 ? username.substring(0, username.indexOf("@")) : username;
        if (shortUserName.length() > USERNAME_MAX_LENGTH - 4) {
            shortUserName = shortUserName.substring(0, USERNAME_MAX_LENGTH - 4);
        }
        // username 长度最大为20个字符，需要截取@符号前字符串，并拼接4位随机数：字母和数据混合，但是总长度不能超过20个字符
        shortUserName = shortUserName + generateRandomString(4);
        registerBody.setShortUserName(shortUserName);
        return shortUserName;
    }

    /**
     * H5 注册
     */
    public void registerH5(RegisterH5Body registerBody) {
        // 入参校验
        validParam(registerBody);
        // 设置默认source
        if (CharSequenceUtil.isBlank(registerBody.getSource())) {
            registerBody.setSource(authConfig.getDefaultSource());
        }
        registerBody.setUsername(registerBody.getEmailAddress());
        String username = registerBody.getEmailAddress();
        String shortUserName = username.substring(0, username.indexOf("@"));
        if (shortUserName.length() > USERNAME_MAX_LENGTH - 4) {
            shortUserName = shortUserName.substring(0, USERNAME_MAX_LENGTH - 4);
        }
        // username 长度最大为20个字符，需要截取@符号前字符串，并拼接4位随机数：字母和数据混合，但是总长度不能超过20个字符
        registerBody.setShortUserName(shortUserName + generateRandomString(4));
        // 注册用户信息
        SysUser sysUser = RegisterMapping.INSTANCE.coverToEntity(registerBody);
        sysUser.setPassword(SecurityUtils.encryptPassword(authConfig.getDefaultH5Pwd()));
        // 设置默认年龄 21岁
        if (Objects.isNull(registerBody.getAge())) {
            registerBody.setAge(DEFAULT_AGE);
        }
        sysUser.setBirthDate(DateUtils.getBirthDateByAge(registerBody.getAge()));
        // h5注册 默认给她一个部门
        sysUser.setDeptId(authConfig.getDefaultDeptId());
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            log.error("register fail：" + registerResult.getMsg());
            // 注册失败，记录错误信息
            recordLogService.recordLogininfor(username, Constants.REGISTER, registerResult.getMsg());
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }
    /**
     * 渠道商 注册
     */
    public Long registerChannel(RegisterChannelBody registerBody) {
        // 入参校验
        validChannelParam(registerBody);
        // 设置默认source
        registerBody.setSource(authConfig.getChannelSource());
        registerBody.setUsername(registerBody.getEmailAddress());
        String username = registerBody.getEmailAddress();
        String shortUserName = username.substring(0, username.indexOf("@"));
        if (shortUserName.length() > USERNAME_MAX_LENGTH - 4) {
            shortUserName = shortUserName.substring(0, USERNAME_MAX_LENGTH - 4);
        }
        // username 长度最大为20个字符，需要截取@符号前字符串，并拼接4位随机数：字母和数据混合，但是总长度不能超过20个字符
        registerBody.setShortUserName(shortUserName + generateRandomString(4));
        // 注册用户信息
        SysUser sysUser = RegisterMapping.INSTANCE.coverChannelToEntity(registerBody);
        // 初始化角色和岗位
        sysUser.setRoleIds(new Long[]{authConfig.getChannelRoleId()});
        sysUser.setPostIds(new Long[]{authConfig.getChannelPostId()});
        sysUser.setPassword(SecurityUtils.encryptPassword(authConfig.getChannelWorkbenchPwd()));
        // 设置默认年龄 21岁
        registerBody.setAge(DEFAULT_AGE);
        sysUser.setBirthDate(DateUtils.getBirthDateByAge(registerBody.getAge()));
        // h5注册 默认给她一个部门
        sysUser.setDeptId(authConfig.getChannelDeptId());
        // 校验业务员是否存在
        String names = String.join(",", registerBody.getExclusiveEmployeeNo(), registerBody.getFollowupEmployeeNo());
        R<List<LoginUser>> listR = innerNetSystemService.getInfos(names);
        if (listR.getCode() != HttpStatus.SUCCESS || Objects.isNull(listR.getData())) {
            throw new ServiceException("No information found for the business employee(" + registerBody.getExclusiveEmployeeNo() + ") and follow-up specialist employee(" + registerBody.getFollowupEmployeeNo() + ").");
        }else {
            Set<String> usernames = listR.getData().stream().map(item -> item.getSysUser().getUserName()).collect(Collectors.toSet());
            checkEmployeeExists(usernames, registerBody.getExclusiveEmployeeNo(), "business");
            checkEmployeeExists(usernames, registerBody.getFollowupEmployeeNo(), "follow-up specialist");
        }
        R<Long> registerResult = remoteUserService.registerForChannel(sysUser, SecurityConstants.INNER);
        if (R.FAIL == registerResult.getCode() || registerResult.getData() <= 0L) {
            log.error("register fail：" + registerResult.getMsg());
            // 注册失败，记录错误信息
            recordLogService.recordLogininfor(username, Constants.REGISTER, registerResult.getMsg());
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
        // 远程调用 渠道商客户信息入库
        Long userId = registerResult.getData();
        ChannelCompanyAddressReq channelAddressReq = ChannelUserMapping.INSTANCE.coverReqToEntity(registerBody);
        channelAddressReq.setUserId(userId);
        // HasInnerNet = false : 外网注册调用
        if(Boolean.FALSE.equals(registerBody.getHasInnerNet())){
            registerBody.setUserId(userId);
            log.info("注册渠道商信息: {}", JSON.toJSONString(registerBody));
            initChannelUserToInner(registerBody);
        }
        return userId;
    }

    private void checkEmployeeExists(Set<String> userNames, String employeeNo, String employeeType) {
        if (!userNames.contains(employeeNo)) {
            throw new ServiceException("No information found for the " + employeeType + " employee(" + employeeNo + ").");
        }
    }

    /**
     * @param registerBody
     */
    private <T extends LoginH5Body> void validParam(T registerBody) {
        // 入参校验
        if (Objects.nonNull(registerBody.getAge()) && registerBody.getAge() < UserConstants.AGE_MIN) {
            throw new ServiceException("Under 18 years old.");
        }
        if (CharSequenceUtil.isBlank(registerBody.getEmailAddress())) {
            // 如果邮箱是空的，则不进行校验
            return;
        }
        if (!StringUtils.isEmailValid(registerBody.getEmailAddress())) {
            throw new ServiceException("Email Address is invalid.");
        }
        if (registerBody.getEmailAddress().length() > UserConstants.EMAIL_MAX_LENGTH) {
            throw new ServiceException("Email length greater than 50.");
        }
    }
    private <T extends LoginChannelBody> void validChannelParam(T registerBody) {
        // 入参校验
        if (Objects.nonNull(registerBody.getAge()) && registerBody.getAge() < UserConstants.AGE_MIN) {
            throw new ServiceException("Under 18 years old.");
        }
        if (CharSequenceUtil.isBlank(registerBody.getEmailAddress())) {
            // 如果邮箱是空的，则不进行校验
            return;
        }
        if (!StringUtils.isEmailValid(registerBody.getEmailAddress())) {
            throw new ServiceException("Email Address is invalid.");
        }
        if (registerBody.getEmailAddress().length() > UserConstants.EMAIL_MAX_LENGTH) {
            throw new ServiceException("Email length greater than 50.");
        }
    }

    /**
     * 同步渠道商至内网
     * @param registerBody
     */
    private void initChannelUserToInner(RegisterChannelBody registerBody) {
        RegisterChannelBodyBO registerChannelBodyBO = new RegisterChannelBodyBO();
        BeanUtils.copyProperties(registerBody, registerChannelBodyBO);
        R<Boolean> result = hiSMKDigDataService.syncChannelUser(registerChannelBodyBO);
        if (result.getCode() != HttpStatus.SUCCESS) {
            throw new ServiceException("register failed: " + result.getMsg());
        }
    }

    public String getUserNameByUuid(String uuid) {
        R<String> result = remoteUserService.getUserNameByUuid(uuid);
        if (Objects.isNull(result) || Objects.isNull(result.getData())) {
            return null;
        }
        return result.getData();
    }

    /**
     * 根据邮箱获取用户名
     *
     * @param email
     * @return
     */
    public String getUserNameByEmail(String email) {
        R<String> result = remoteUserService.getUserNameByEmail(email);
        if (Objects.isNull(result) || Objects.isNull(result.getData())) {
            return null;
        }
        return result.getData();
    }

    public Map<String, Object> registerAndLoginForThird(RegisterH5Body registerBody, AuthUser authUser) {
        log.info("registerH5 registerBody: {}", JSON.toJSONString(registerBody));
        String channel = ServletUtils.getRequest().getHeader(SecurityConstants.CHANNEL_KEY);
        String deviceId = ServletUtils.getRequest().getHeader(SecurityConstants.DEVICE_KEY);
        if (Objects.isNull(DeviceIdEnum.getNameByCode(deviceId))) {
            log.error("deviceId value is error.");
            throw new ServiceException("deviceId value is error.");
        }
        if (Objects.isNull(ChannelEnum.getNameByCode(channel))) {
            log.error("channel value is error.");
            throw new ServiceException("channel value is error.");
        }
        // 用户注册
        this.registerForThird(registerBody, authUser);
        return loginForH5(registerBody, channel, deviceId);
    }

    /**
     * 登录 ，并发送30积分福利
     *
     * @param registerBody
     * @param channel
     * @param deviceId
     * @return
     */
    private Map<String, Object> loginForH5(RegisterH5Body registerBody, String channel, String deviceId) {
        // 用户登录
        LoginUser userInfo = this.login(registerBody.getShortUserName());
        // 获取登录用户ID
        SysUser sysUser = userInfo.getSysUser();
        sysUser.setRoleIds(new Long[]{authConfig.getDefaultRoleId()});
        sysUser.setPostIds(new Long[]{authConfig.getDefaultDeptId()});
        // 初始化角色和岗位
        remoteUserService.initH5UserRoleAndPost(userInfo.getSysUser());
        // 获取登录token
        Map<String, Object> result = tokenService.createToken(userInfo, channel, deviceId);
        result.put("username", registerBody.getShortUserName());
        // 查询age数据
        result.put("age", DateUtils.getAgeByBirthDate(sysUser.getBirthDate()));
        // userId
        result.put(AuthConstants.USER_ID, sysUser.getUserId());
        // 积分福利获取
        // 发送注册成功福利  （去掉扫码方式判定）
        // 增加特殊逻辑，如果是 特殊source标识，则进行 100积分注册赠送
        sendRegisterPointsMQ(registerBody, sysUser);
        // 发送注册成功福利
//        if (CharSequenceUtil.isNotBlank(registerBody.getEvaluateType())
//                && EvaluateTypeEnum.SCAN_CODE.getEvaluateType().equals(registerBody.getEvaluateType())) {
//            String brand = ServletUtils.getRequest().getHeader(SecurityConstants.BRAND_KEY);
//            remotePointBalanceService.scanRegister(sysUser, brand);
//        } else {
//            log.info("registerH5 getEvaluateType: {}", registerBody.getEvaluateType());
//        }
        return result;
    }

    /**
     * 注册积分 MQ配送
     *
     * @param registerBody
     * @param sysUser
     */
    private void sendRegisterPointsMQ(RegisterH5Body registerBody, SysUser sysUser) {
        String brand = ServletUtils.getRequest().getHeader(SecurityConstants.BRAND_KEY);
        SourcePointsVO sourcePointsVO = sourcePointsConfig.getBySource(registerBody.getSource());
        ScanRegisterVO scanRegisterVO = new ScanRegisterVO();
        scanRegisterVO.setUserId(sysUser.getUserId());
        scanRegisterVO.setBrand(brand);
        scanRegisterVO.setPoints(Objects.isNull(sourcePointsVO) ? null : sourcePointsVO.getPoints());
        remotePointBalanceService.scanRegister(scanRegisterVO, brand);
    }

    public Map<String, Object> registerAndLogin(RegisterH5Body registerBody) {
        log.info("registerH5 registerBody: {}", JSON.toJSONString(registerBody));
        String channel = ServletUtils.getRequest().getHeader(SecurityConstants.CHANNEL_KEY);
        String deviceId = ServletUtils.getRequest().getHeader(SecurityConstants.DEVICE_KEY);
        if (Objects.isNull(DeviceIdEnum.getNameByCode(deviceId))) {
            log.error("deviceId value is error.");
            throw new ServiceException("deviceId value is error.");
        }
        if (Objects.isNull(ChannelEnum.getNameByCode(channel))) {
            log.error("channel value is error.");
            throw new ServiceException("channel value is error.");
        }
        // 设置IP
        registerBody.setRegisterIp(IpUtils.getIpAddr());
        // 用户注册
        this.registerH5(registerBody);
        return loginForH5(registerBody, channel, deviceId);
    }

    public Long channelRegister(RegisterChannelBody registerBody) {
        log.info("channelRegister registerBody: {}", JSON.toJSONString(registerBody));
        // 设置IP
        registerBody.setRegisterIp(IpUtils.getIpAddr());
        // 用户注册
        return this.registerChannel(registerBody);
    }

    public Map<String, Object> loginOnlyForH5(String username) {
        String channel = ServletUtils.getRequest().getHeader(SecurityConstants.CHANNEL_KEY);
        String deviceId = ServletUtils.getRequest().getHeader(SecurityConstants.DEVICE_KEY);
        if (Objects.isNull(DeviceIdEnum.getNameByCode(deviceId))) {
            log.error("deviceId value is error.");
            throw new ServiceException("deviceId value is error.");
        }
        if (Objects.isNull(ChannelEnum.getNameByCode(channel))) {
            log.error("channel value is error.");
            throw new ServiceException("channel value is error.");
        }
        // 用户登录
        LoginUser userInfo = this.login(username);
        // 删除token
        tokenService.delLoginUserCache(userInfo.getSysUser().getUserId(), channel, deviceId);
        // 获取登录token
        Map<String, Object> result = tokenService.createToken(userInfo, channel, deviceId);
        // 查询age数据
        SysUser sysUser = userInfo.getSysUser();
        Integer age = DateUtils.getAgeByBirthDate(sysUser.getBirthDate());
        result.put("age", age);
        return result;
    }

    public Map<String, Object> loginOnly(String username) {
        String channel = ServletUtils.getRequest().getHeader(SecurityConstants.CHANNEL_KEY);
        String deviceId = ServletUtils.getRequest().getHeader(SecurityConstants.DEVICE_KEY);
        return loginOnly(username, channel, deviceId);
    }

    public Map<String, Object> loginOnly(String username, String channel, String deviceId) {
        if (Objects.isNull(DeviceIdEnum.getNameByCode(deviceId))) {
            log.error("deviceId value is error.");
            throw new ServiceException("deviceId value is error.");
        }
        if (Objects.isNull(ChannelEnum.getNameByCode(channel))) {
            log.error("channel value is error.");
            throw new ServiceException("channel value is error.");
        }
        // 用户登录
        LoginUser userInfo = this.login(username);
        // 删除token
        tokenService.delLoginUserCache(userInfo.getSysUser().getUserId(), channel, deviceId);
        // 获取登录token
        return tokenService.createToken(userInfo, channel, deviceId);
    }
}
